package com.example.tests;


import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent;

import org.openqa.selenium.*;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.example.pages.InternalPage;
import com.example.pages.LoginPage;
import com.example.pages.UserManagmentPage;
import com.example.pages.UserPage;

import ru.esteru.selenium.factory.WebDriverFactory;

public class ChangeEmailTest {
  private WebDriver driver;
  private WebDriverWait wait;
  private String baseUrl;
  private StringBuffer verificationErrors = new StringBuffer();
  private InternalPage somePage;
  private LoginPage loginPage;
  private UserPage userPage;
  private UserManagmentPage userManagmentPage;

  @Before
  public void setUp() throws Exception {
	  driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
      baseUrl = "http://localhost/";
      wait = new WebDriverWait(driver, 10);
      driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  }

 
  @Test
  public void emailChangeTest() {
	    goToMainPage();
	    loginAs("admin", "admin");
	    goToUserPrifile();
	    changeEmailTo("admin@admin.ru");	   
	    assertTrue(isOnUserManagmentPage());
	    logout();
  }

private boolean isOnUserManagmentPage() {
	return userManagmentPage.pageTitle.getText().equals("User management");
}

private void changeEmailTo(String newEmail)  {
	userPage.emailField.clear();
	userPage.emailField.sendKeys(newEmail);
	userPage.saveButton.click();
}

private void goToUserPrifile() {
	somePage.menuMyProfileLink.click();
}

private void logout() {
	somePage.menuLogoutLink.click();
	wait.until(alertIsPresent()).accept();
}

private void loginAs(String username, String password) {
	loginPage.userNameField.clear();
    loginPage.userNameField.sendKeys(username);
    loginPage.passwordField.clear();
    loginPage.passwordField.sendKeys(password);
    loginPage.loginButton.click();
}

private void goToMainPage() {
	driver.get(baseUrl + "/php4dvd/");
	loginPage = PageFactory.initElements(driver, LoginPage.class);
	somePage = PageFactory.initElements(driver, InternalPage.class);
	userPage = PageFactory.initElements(driver, UserPage.class);
	userManagmentPage = PageFactory.initElements(driver, UserManagmentPage.class);
}

  @After
  public void tearDown() throws Exception {
    String verificationErrorString = verificationErrors.toString();
    if (!"".equals(verificationErrorString)) {
      fail(verificationErrorString);
    }
  }
}
